<?php
/**
 * This sample service contains functions that illustrate typical
 * service operations. This code is for prototyping only.
 *
 *  Authenticate users before allowing them to call these methods.
 */

class VocabService {
  var $username = "root";
  var $password = "";
  var $server = "localhost";
  var $port = "3306";
  var $databasename = "voc_db";
  var $tablename = "vocabu";

  var $connection;

  /*
   *
   CREATE TABLE `testdrive_db`.`vocabularies` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`engl` VARCHAR( 255 ) NOT NULL ,
`swed` VARCHAR( 255 ) NOT NULL
) ENGINE = MYISAM CHARACTER SET latin1 COLLATE latin1_swedish_ci;
   */

  public function __construct() {
    $this->connection = mysqli_connect(
                       $this->server,
                       $this->username,
                       $this->password,
                       $this->databasename,
                       $this->port
                       );

    $this->throwExceptionOnError($this->connection);
  }

  public function getVocabularies() {
     $stmt = mysqli_prepare($this->connection,
          "SELECT vocabu.id, vocabu.engl, vocabu.swed  FROM `vocabu`");

      $this->throwExceptionOnError();

      mysqli_stmt_execute($stmt);
      $this->throwExceptionOnError();

      $rows = array();
      mysqli_stmt_bind_result($stmt , $row->id, $row->engl, $row->swed);

      while (mysqli_stmt_fetch($stmt)) {
          $rows[] = $row;
          $row = new stdClass();
          mysqli_stmt_bind_result($stmt, $row->id, $row->engl, $row->swed);
      }

      mysqli_stmt_free_result($stmt);
      mysqli_close($this->connection);

      return $rows;
  }

/**
  * Utitity function to throw an exception if an error occurs
  * while running a mysql command.
  */
  private function throwExceptionOnError($link = null) {
    if($link == null) {
      $link = $this->connection;
    }
    if(mysqli_error($link)) {
      $msg = mysqli_errno($link) . ": " . mysqli_error($link);
      throw new Exception('MySQL Error - '. $msg);
    }
  }

}
?>
